package com.exam.controller;

import com.exam.dto.ActionResult;
import com.exam.po.Admin;
import com.exam.po.Student;
import com.exam.po.Teacher;
import com.exam.service.LoginService;
import com.exam.service.TeacherService;
import com.exam.utils.JwtUtils;
import com.exam.vo.Login;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhanggaoxiang
 * @ClassName LoginController
 * @Description TODO
 * @Date 2021/1/11 14:35
 * @Version 1.0
 **/
@RestController
@Slf4j
@RequestMapping("/api")
public class LoginController {

    @Resource
    private LoginService loginService;


    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ActionResult login(@RequestBody Login login){
        //获取参数  以及 定义变量
        Integer username = login.getUsername();
        String password = login.getPassword();
        Map data = new HashMap();
        String token;
        String msg;

        Admin admin = loginService.findAdminByIdAndPassword(username,password);
        if(admin!=null && "0".equals(admin.getRole())){
            msg = "欢迎您!尊贵的管理员";
            token = JwtUtils.sign(admin.getRole());
            data.put("token",token);
            data.put("role",admin.getRole());
            data.put("userid",admin.getAdminid());
            data.put("username",admin.getAdminname());
            return new ActionResult(200,msg,data);
        }
        Teacher teacher = loginService.findTeacherByIdAndPassword(username,password);
        if(teacher!=null && "1".equals(teacher.getRole())){
            msg = "欢迎您!"+teacher.getTeachername()+"老师";
            token = JwtUtils.sign(teacher.getRole());
            data.put("token",token);
            data.put("role",teacher.getRole());
            data.put("userid",teacher.getTeacherid());
            data.put("username",teacher.getTeachername());
            return new ActionResult(200,msg,data);
        }
        Student student = loginService.findStudentByIdAndPassword(username,password);
        if(student!=null && "2".equals(student.getRole())){
            msg = "欢迎您!"+student.getStudentname()+"同学";
            token = JwtUtils.sign(student.getRole());
            data.put("token",token);
            data.put("role",student.getRole());
            data.put("userid",student.getStudentid());
            data.put("username",student.getStudentname());
            return new ActionResult(200,msg,data);
        }
        msg = "登陆失败!查无此人!";
        return new ActionResult(500,msg,null);
    }

}
